//
//  huafeiViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/6/11.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "RechargeController.h"

#import "InputPhoneView.h"
#import "ChooseMoneyView.h"
#import "PayModeView.h"
#import "JudgePhoneNumberBelong.h"
#import "OrderPaymentController.h"
#import "CreatStochasticOrderNumber.h"
#import "LogInViewController.h"

#define BelongLabelText @"手机号码归属地"
#define ErrorBelongLabelText @"请输入正确的手机号码"


@interface RechargeController ()<ChooseMoneyViewDelegate,UITextFieldDelegate,PayModeViewDelegate>
@property(nonatomic,strong)XRCarouselView *XrCarouselView;

@property (nonatomic,strong)UITextField *phoneNumberTextField;

@property (nonatomic,strong)UILabel *belongLabel;

@property(nonatomic,copy)NSString *chooseMoney;

@property (nonatomic,strong)NSArray *cycleUrlArray;

@property (nonatomic,strong)NSMutableArray *chooseArray;

@property(nonatomic,strong)UIButton *btn;

@end

@implementation RechargeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BACKGROUND_COLOR;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self homeCycleViewPictureUrl];
    [self addViews];
    [self showHudInView:self.view hint:nil];
    
}

- (void)homeCycleViewPictureUrl
{
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"position":@"15"} AndMenthodName:@"/api/Ads/appAd" completeBlock:^(id object) {
//        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            self.cycleUrlArray = [object objectForKey:@"data"];
        }
    }];
    
}

- (void)addViews
{
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"position":@"15"} AndMenthodName:@"/api/Ads/appAd" completeBlock:^(id object) {
        //        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            self.cycleUrlArray = [object objectForKey:@"data"];
            
            NSMutableArray *imageArr = [NSMutableArray array];
            for (NSDictionary *tempDict in self.cycleUrlArray) {
                NSString *str = tempDict[@"ad_code"];
                [imageArr addObject:str];
            }
            
            NSLog(@"%@",imageArr);
            
            if (_XrCarouselView == nil || imageArr.count > 0) {
                _XrCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/6) imageArray:imageArr];
                self.XrCarouselView.time = 2;
                [self.view addSubview:self.XrCarouselView];
                
            }
        }
    }];
    
    //适配
    CGFloat margin = 5;
    CGFloat inputCount;
    CGFloat chooseCount;
    if (iPhone5) {
        inputCount = 10;
        chooseCount = 7;
    }else {
        inputCount = 9;
        chooseCount = 6;
    }
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"type":@"1",@"client_type":@"2"} AndMenthodName:@"/api/card/index" completeBlock:^(id object) {
        [self hideHud];
        InputPhoneView *inputView = [[InputPhoneView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(self.XrCarouselView.frame)+margin,WIDTH, HEIGHT/8)];
        self.phoneNumberTextField = inputView.phoneNumText;
        self.phoneNumberTextField.delegate = self;
        [self.phoneNumberTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        self.belongLabel = inputView.belongLabel;
        [self.view addSubview:inputView];
        
        self.chooseArray = [object objectForKey:@"data"];
        self.chooseMoney = self.chooseArray.firstObject[@"dynamic_price"];
        ChooseMoneyView *chooseView = [[ChooseMoneyView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(inputView.frame)+margin, WIDTH, HEIGHT/chooseCount)];
        [self.view addSubview:chooseView];
        chooseView.chooseArray = self.chooseArray;
        chooseView.delegate = self;

        PayModeView *payView = [[PayModeView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(chooseView.frame), WIDTH,HEIGHT-self.XrCarouselView.Height-chooseView.Height- inputView.Height-margin*3)];
        payView.delegate = self;
        [self.view addSubview:payView];
        self.btn = payView.payBtn;
    }];
    
}


- (void)textFieldDidChange:(UITextField *)textField
{
    
    if (textField == self.phoneNumberTextField) {
        if (textField.text.length >=11) {
            textField.text = [textField.text substringToIndex:11];
        }
        if (textField.text.length >10) {
            NSLog(@"调方法");
            [self resignResponderTextField];
            [self receiveMessage:self.phoneNumberTextField.text];
        } else {
            self.belongLabel.text = BelongLabelText;
        }
    }
    
}

/*
 code = 1;
 data = "\U4e2d\U56fd\U8054\U901a";
 message =     {
 msg = "";
 view = "";
 };
 */
- (void)receiveMessage:(NSString *)phoneStr {
    NSString *account = phoneStr;
    
    NSDictionary *param = @{@"account":[NSString stringWithFormat:@"%@", account]};
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:param AndMenthodName:@"/api/Com/mobileInfo" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        
        NSString *string = [object objectForKey:@"data"];
        
        if (![string isEqual:@0]) {
            self.belongLabel.text = [object objectForKey:@"data"];
        } else {
            self.belongLabel.text = ErrorBelongLabelText;
        }

    }];

    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self resignResponderTextField];
}

- (void)resignResponderTextField {
    [self.phoneNumberTextField resignFirstResponder];
}

#pragma mark >>>>>>>>>>ChooseMoneyView代理
- (void)ChooseMoneyViewDidClick:(UIButton *)button
{
    
    [self resignResponderTextField];
    
//    if (button.tag == 1000) {
//        self.chooseMoney = @"30";
//    }else if (button.tag == 1001){
//        self.chooseMoney = @"50";
//    }else{
//        self.chooseMoney = @"100";
//    }
    
    self.chooseMoney = [self.chooseArray[button.tag - 1000] objectForKey:@"dynamic_price"];
    
}

//立即支付
- (void)payModeViewDidClick
{
    if (!USERNAME) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            accountVC.JudgeLogInBack = NO;
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    [self.btn setBackgroundColor:[UIColor lightGrayColor]];
    [self.btn setEnabled:false];


//    http://www.dev.ylgw8.com/api/Order/createOrderId?username=18000000000&business_tpye=call_charges&account=18620614920&jine=30&yys=中国联通
    
        if ([self.belongLabel.text isEqualToString:BelongLabelText] || [self.belongLabel.text isEqualToString:ErrorBelongLabelText]) {
    
//    if ([self.belongLabel.text isEqualToString:ErrorBelongLabelText]) {
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请输入正确的手机号码" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        return;
    }
    
    
    [self.btn setBackgroundColor:[UIColor lightGrayColor]];
    [self.btn setEnabled:false];
    
    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"business_type":@"call_charges",
                             @"phone":self.phoneNumberTextField.text,
                             @"money":self.chooseMoney,
                             @"yys":self.belongLabel.text,
                             };
    
    NSLog(@"%@",params);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/createOrderId" completeBlock:^(id object) {
            NSLog(@"%@",object);
            
            if(JudgeBackDataCode) {
                NSString *orderNumber = [object objectForKey:@"data"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    OrderPaymentController *OrderPaymentVC = [[OrderPaymentController alloc] init];
                    
                    OrderPaymentVC.OrderString = orderNumber;
                    OrderPaymentVC.OrderTitleString = @"话费充值";
                    OrderPaymentVC.OrderDescribeInfo = self.phoneNumberTextField.text;
                    OrderPaymentVC.orderType = @"1";
                    OrderPaymentVC.OrderMonryString = self.chooseMoney;
                    OrderPaymentVC.judgeRecharge = YES;
                    
                    [self.navigationController pushForm:self.navigationController pushToAndHidden:OrderPaymentVC];
                });
            } else if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqualToString:@"-9000"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *MessageDict = [object objectForKey:@"message"];
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:MessageDict[@"view"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        MyAccountTableViewController *accountVC = [[MyAccountTableViewController alloc] init];
                        [self.navigationController pushForm:self.navigationController pushToAndHidden:accountVC];
                    }];
                    [alert addAction:SettingAction];
                    
                    
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancelAction];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                    
                });
            } else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *MessageDict = [object objectForKey:@"message"];
                    
                    MBProgressHUD *hud = [MBProgressHUD showMessage:MessageDict[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                    [self.view addSubview:hud];
                    
                });
                
            }
            
            [self.btn setBackgroundColor:DEFAULT_COLOR];
            [self.btn setEnabled:true];
            
        }];
    });
    
}


#pragma mark>>>>>>>>>>懒加载轮播
- (XRCarouselView *)XrCarouselView
{
    if (!_XrCarouselView) {
//        NSArray *imageArr = @[
//                              [UIImage imageNamed:@"vn2.jpg"],
//                              [UIImage imageNamed:@"vn3.jpg"],
//                              [UIImage imageNamed:@"vn1.jpg"]
//                              ];
        
        NSMutableArray *imageArr = [NSMutableArray array];
        for (NSDictionary *tempDict in self.cycleUrlArray) {
            NSString *str = tempDict[@"ad_code"];
            [imageArr addObject:str];
        }
        
        if (_XrCarouselView == nil || imageArr.count > 0) {
            _XrCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/6) imageArray:imageArr];
            self.XrCarouselView.delegate = self;
            self.XrCarouselView.time = 2;
            [self.view addSubview:self.XrCarouselView];
        }
    }
    return _XrCarouselView;
}

- (NSArray *)cycleUrlArray {
    if (!_cycleUrlArray) {
        _cycleUrlArray = [NSArray array];
    }
    return _cycleUrlArray;
}

- (NSMutableArray *)chooseArray {
    if (!_chooseArray) {
        _chooseArray = [NSMutableArray array];
    }
    return _chooseArray;
}

@end
